package com.tange.ai.iot.client.gnssa.play.multi

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.*
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.Gravity
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityDeviceLiveThreeChannelBinding
import com.tange.base.toolkit.*
import com.tange.core.device.facade.ConnectStatus
import com.tange.core.device.facade.DeviceFacade
import com.tange.core.device.facade.Status
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.live.SharedChannelDeviceLiveMediaSource
import com.tange.core.trouble.shooting.entry.DebuggingAssistant
import com.tg.appcommon.android.TGLog
import com.tg.data.media.AvSyncController
import java.io.File

/**
 * 多视频通道的设备直播页面展示（多路视频使用同一个通道进行传输）
 *
 * 此处 演示 3 个通道。
 *
 * 如有更多通道的需求，比如3、4、5、6 个，自行参考处理即可。
 *
 * 注意：仅演示视频播放，其余截屏等功能参考 DeviceLiveActivity
 */
class SharedChannelDeviceLiveActivity : AppCompatActivity() {
    private var albumPath = Environment.getExternalStorageDirectory()
        .toString() + File.separator + Environment.DIRECTORY_DCIM

    companion object {
        private const val TAG = "SharedChannelDeviceLiveActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, SharedChannelDeviceLiveActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDeviceLiveThreeChannelBinding

    private lateinit var deviceFacade: DeviceFacade

    private lateinit var deviceLiveMediaSource: SharedChannelDeviceLiveMediaSource

    /**
     * 视频通道-0
     */
    private lateinit var deviceMediaRender_0: DeviceMediaRender

    /**
     * 视频通道-1
     */
    private lateinit var deviceMediaRender_1: DeviceMediaRender


    /**
     * 视频通道-2
     */
    private lateinit var deviceMediaRender_2: DeviceMediaRender

    private var screenRecordMediaRenders  = ArrayList<DeviceMediaRender>()
    private var rendered = false

    private lateinit var connectStatusObserver : Consumer<ConnectStatus>

    private  var avSyncController : AvSyncController = AvSyncController()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDeviceLiveThreeChannelBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            com.tange.ai.iot.client.gnssa.utils.Utils.setDarkStatusBar(this@SharedChannelDeviceLiveActivity, Color.TRANSPARENT)
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!
// 初始化调试助手，设置 顶部的 标题 为触发入口
        DebuggingAssistant.attach(this, binding.name).apply {
            deviceId = this@SharedChannelDeviceLiveActivity.deviceId
        }
        connectStatusObserver = Consumer<ConnectStatus> {
            TGLog.i(TAG, "[connect-status] ${it.status}")
            ui {
                if (it.status != Status.SUCCESS) {
                    if (it.status == Status.DISCONNECTED_BY_DEVICE) {
                        Tips.show("设备侧主动断开了连接，将在3秒后自动关闭页面")
                        binding.loading.postDelayed({
                            finish()
                        }, 3000L)
                    } else if (it.status == Status.FAILED) {
                        binding.loading.gone()
                        binding.connect.visible()
                        binding.connect.text = "重试"
                        Tips.show("连接失败：$it")
                    } else {
                        binding.loading.visible()
                    }
                } else {
                    if (rendered) {
                        binding.loading.gone()
                    }
                }
            }
        }

        // 创建设备交互模块
        deviceFacade = DeviceFacade(deviceId).apply {

            // 监听连接状态变化
            observeConnectStatus(connectStatusObserver)
        }

        configureVideoChannel_0()
        configureVideoChannel_1()
        configureVideoChannel_2()

        binding.loading.visible()
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
            R.drawable.ic_baseline_volume_off_24
        ))
        binding.audio.onClicked { switchAudio() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked {
            binding.connect.gone()
            deviceFacade.connect()
        }

        binding.resolutions.visible()
        binding.resolutions.onClicked { queryResolutions() }

        binding.card.onClicked { ThreeChannelDevicePlaybackActivity.launch(it.context, deviceId) }
        binding.cloud.onClicked { MultiChannelCloudPlaybackActivity.launch(it.context, deviceId) }
        binding.screenRecord.onClicked {
            if (screenRecordMediaRenders.size == 0) {
                Tips.show("请先点击需要录像的画面，再点击录像按钮,支持多路同时录像")
                return@onClicked
            }
            screenRecordMediaRenders.forEach {
                screenRecord(it)
            }
        }

    }

    /**
     * 配置视频通道-1
     */
    private fun configureVideoChannel_0() {
        // 创建实时媒体数据源
        deviceLiveMediaSource = SharedChannelDeviceLiveMediaSource(deviceFacade).apply {
            cameraIndexSet.add(0)
            cameraIndexSet.add(1)
            cameraIndexSet.add(2)
        }

        // 创建媒体播放器
        deviceMediaRender_0 = DeviceMediaRender(this, deviceLiveMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(0)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer0, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }
            setAvSyncController(avSyncController)
            mute(true)
        }
        binding.playerContainer0.onClicked {
            if (!screenRecordMediaRenders.contains(deviceMediaRender_0)){
                screenRecordMediaRenders.add(deviceMediaRender_0)
                Tips.show("添加录像序号为 0")
            }else {
                screenRecordMediaRenders.remove(deviceMediaRender_0)
                Tips.show("移除录像序号为 0")
            }
        }
    }

    /**
     * 配置视频通道-2
     */
    private fun configureVideoChannel_1() {

        // 创建媒体播放器
        deviceMediaRender_1 = DeviceMediaRender(this, deviceLiveMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(1)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer1, createCenterLayoutParams())
            setAvSyncController(avSyncController)
            enableAudio(false)
        }
        binding.playerContainer1.onClicked {
            if (!screenRecordMediaRenders.contains(deviceMediaRender_1)){
                screenRecordMediaRenders.add(deviceMediaRender_1)
                Tips.show("添加录像序号为 1")
            }else {
                screenRecordMediaRenders.remove(deviceMediaRender_1)
                Tips.show("移除录像序号为 1")
            }

        }
    }

    /**
     * 配置视频通道-2
     */
    private fun configureVideoChannel_2() {

        // 创建媒体播放器
        deviceMediaRender_2 = DeviceMediaRender(this, deviceLiveMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(2)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer2, createCenterLayoutParams())
            setAvSyncController(avSyncController)
            enableAudio(false)
        }
        binding.playerContainer2.onClicked {
            if (!screenRecordMediaRenders.contains(deviceMediaRender_2)){
                screenRecordMediaRenders.add(deviceMediaRender_2)
                Tips.show("添加录像序号为 2")
            }else {
                screenRecordMediaRenders.remove(deviceMediaRender_2)
                Tips.show("移除录像序号为 2")
            }
        }
    }

    @SuppressLint("LongLogTag")
    private fun queryResolutions() {

            if (!deviceFacade.connected()) {
                Tips.show("设备未连接！")
                return
            }

            deviceLiveMediaSource.querySupportedResolutions {
                Log.i(SharedChannelDeviceLiveActivity.TAG, "[queryResolutions] $it")
                ui {
                    if (it.success) {
                        val resolutions = it.data!!
                        val currentResolution = deviceLiveMediaSource.currentVideoResolution()
                        var currentIndex = 0
                        resolutions.forEachIndexed { index, liveResolutions ->
                            if (liveResolutions.value == currentResolution) {
                                currentIndex = index
                            }
                        }
                        val items = Array(resolutions.size) { index -> if (index == currentIndex) "${resolutions[index].label} [当前]" else resolutions[index].label }

                        AlertDialog.Builder(this@SharedChannelDeviceLiveActivity)
                            .setTitle("选择视频码流")
                            .setItems(items) { _, which ->
                                run {
                                    Tips.show("切换至 ${resolutions[which].label} ...")
                                    deviceLiveMediaSource.cameraIndexSet.forEach { cameraIndex ->
                                        deviceLiveMediaSource.switchVideoResolution(cameraIndex, resolutions[which].value)
                                    }
                                }
                            }
                            .create()
                            .show()

                    } else {
                        Tips.show("查询码流设置失败 ${it.message}")
                    }
                }
            }


    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")

        deviceLiveMediaSource.enableVideoProduce(true)

        deviceMediaRender_0.enableVideoRender(true)
        deviceMediaRender_1.enableVideoRender(true)
        deviceMediaRender_2.enableVideoRender(true)
    }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")

        deviceLiveMediaSource.enableVideoProduce(false)

        deviceMediaRender_0.enableAudioRender(false)
        deviceMediaRender_0.enableVideoRender(false)

        deviceMediaRender_1.enableAudioRender(false)
        deviceMediaRender_1.enableVideoRender(false)

        deviceMediaRender_2.enableAudioRender(false)
        deviceMediaRender_2.enableVideoRender(false)

        binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24))
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceFacade.disconnect()
        deviceFacade.unObserveConnectStatus(connectStatusObserver)
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun switchAudio() {
        if (deviceLiveMediaSource.isAudioProduceEnabled()) {
            binding.audio.setImageDrawable(
                ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24)
            )
            deviceLiveMediaSource.enableAudioProduce(false)
            deviceMediaRender_0.enableAudioRender(false)
        } else {
            binding.audio.setImageDrawable(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_baseline_volume_on_24
                )
            )
            deviceLiveMediaSource.enableAudioProduce(true)
            deviceMediaRender_0.enableAudioRender(true)
        }
    }
    @SuppressLint("LongLogTag")
    private fun screenRecord(deviceMediaRender :DeviceMediaRender) {

        if (!deviceMediaRender.playing) {
            Tips.show("当前未在播放！")
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(arrayOf(Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_VIDEO), 100)
                Tips.show("需要存储权限")
                return
            }
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    this.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
                }
                Tips.show("需要存储权限")
                return
            }
        }
        if (deviceMediaRender.screenRecord().isStarted()) {
            val file = File(albumPath, "TG-${System.currentTimeMillis()}.mp4")
            deviceMediaRender.screenRecord().finish(file.absolutePath) {
                if (it) Tips.show("录屏已保存到 ${file.absolutePath}")
            }
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_video_record_normal
            ))
        } else {
            deviceMediaRender.screenRecord().start()
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_video_record_on
            ))
            Tips.show("开始录屏，再次点击结束录屏")
        }

        Log.i(TAG, "[RecordStatusObserver][onClicked] ")
    }
}